package com.jlnk.rxjavademo2.presenter;

import com.jlnk.rxjavademo2.client.WeatherRetrofitClient;
import com.jlnk.rxjavademo2.entity.WeatherEntity;
import com.jlnk.rxjavademo2.service.WeatherService;
import com.jlnk.rxjavademo2.view.WeatherView;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.disposables.CompositeDisposable;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class WeatherPresenter {
    private WeatherView view;
    private WeatherService weatherService;
    private CompositeDisposable compositeDisposable;

    public WeatherPresenter(WeatherView view, String apiKey) {
        this.view = view;
        weatherService = WeatherRetrofitClient.getInstance().create(WeatherService.class);
        compositeDisposable = new CompositeDisposable();
    }

    public void loadWeatherInfo(String city, String state, String country) {
        view.showLoading();
        compositeDisposable.add(weatherService.getCurrentWeather("aea1852529f64cc6bdc6a81da2e0b9db", city, state, country)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(this::onWeatherInfoSuccess, this::onError));
    }

    private void onWeatherInfoSuccess(WeatherEntity response) {
        view.hideLoading();
        if (response.getWeatherDataList() != null && !response.getWeatherDataList().isEmpty()) {
            WeatherEntity.WeatherData weatherData = response.getWeatherDataList().get(0);
            view.showWeatherInfo(weatherData);
        } else {
            view.showError("No weather data available");
        }
    }

    private void onError(Throwable throwable) {
        view.hideLoading();
        view.showError(throwable.getMessage());
    }
}